package com.example.teaching_server.controller;

import com.example.teaching_server.common.ApiResponse;
import com.example.teaching_server.dto.SidebarItemDTO;
import com.example.teaching_server.entity.CourseEntity;
import com.example.teaching_server.service.CourseService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/api/courses")
@RequiredArgsConstructor
@Tag(name = "课程管理", description = "课程信息查询和管理接口")
public class CourseController {
    private final CourseService courseService;

    /**
     * 获取侧边栏项目
     */
    @GetMapping("/sidebar")
    @Operation(summary = "获取侧边栏项目", description = "根据类型获取侧边栏显示的项目列表")
    public ApiResponse<List<SidebarItemDTO>> getSidebarItems(
            @Parameter(description = "侧边栏类型")
            @RequestParam String type) {
        log.info("开始获取侧边栏项目: type={}", type);

        try {
            List<SidebarItemDTO> data = courseService.getSidebarItems(type);
            log.info("成功获取{}个侧边栏项目", data.size());
            return ApiResponse.success("数据获取成功", data);
        } catch (Exception e) {
            log.error("获取侧边栏项目失败: type={}", type, e);
            return ApiResponse.fail("获取侧边栏项目失败: " + e.getMessage());
        }
    }

    /**
     * 获取所有课程
     */
    @GetMapping
    @Operation(summary = "获取课程列表", description = "获取所有课程的详细信息")
    public ApiResponse<List<CourseEntity>> getAllCourses() {
        log.info("开始获取课程列表");

        try {
            List<CourseEntity> courses = courseService.getAllCourses();
            log.info("成功获取{}个课程", courses.size());
            return ApiResponse.success("课程列表获取成功", courses);
        } catch (Exception e) {
            log.error("获取课程列表失败", e);
            return ApiResponse.fail("获取课程列表失败: " + e.getMessage());
        }
    }

    /**
     * 按类别获取课程
     */
    @GetMapping("/by-category")
    @Operation(summary = "按类别获取课程", description = "根据课程类别筛选课程列表")
    public ApiResponse<List<CourseEntity>> getCoursesByCategory(
            @Parameter(description = "课程类别")
            @RequestParam String category) {
        log.info("开始按类别获取课程: category={}", category);

        try {
            List<CourseEntity> courses = courseService.getCoursesByCategory(category);
            log.info("成功获取{}类别的{}个课程", category, courses.size());
            return ApiResponse.success(category + "课程列表获取成功", courses);
        } catch (Exception e) {
            log.error("按类别获取课程失败: category={}", category, e);
            return ApiResponse.fail("按类别获取课程失败: " + e.getMessage());
        }
    }

    /**
     * 获取所有课程类别
     */
    @GetMapping("/categories")
    @Operation(summary = "获取课程类别", description = "获取所有可用的课程类别列表")
    public ApiResponse<List<Map<String, Object>>> getAllCourseCategories() {
        log.info("开始获取课程类别列表");

        try {
            List<Map<String, Object>> categories = courseService.getAllCourseCategories();
            log.info("成功获取{}个课程类别", categories.size());
            return ApiResponse.success("课程类别列表获取成功", categories);
        } catch (Exception e) {
            log.error("获取课程类别失败", e);
            return ApiResponse.fail("获取课程类别失败: " + e.getMessage());
        }
    }

    /**
     * 搜索课程
     */
    @GetMapping("/search")
    @Operation(summary = "搜索课程", description = "根据类别和关键词搜索课程")
    public ApiResponse<List<CourseEntity>> searchCourses(
            @Parameter(description = "课程类别")
            @RequestParam(required = false) String category,
            @Parameter(description = "搜索关键词")
            @RequestParam(required = false) String keyword) {
        log.info("开始搜索课程: category={}, keyword={}", category, keyword);

        try {
            List<CourseEntity> courses;

            // 如果提供了类别，按类别筛选
            if (category != null && !category.trim().isEmpty()) {
                courses = courseService.getCoursesByCategory(category);

                // 如果同时有关键字，进行二次筛选
                if (keyword != null && !keyword.trim().isEmpty()) {
                    courses = courses.stream()
                            .filter(course ->
                                    course.getCourseName().toLowerCase().contains(keyword.toLowerCase()) ||
                                            (course.getCategory() != null &&
                                                    course.getCategory().toLowerCase().contains(keyword.toLowerCase())))
                            .collect(Collectors.toList());
                }
            }
            // 如果只有关键字，全局搜索
            else if (keyword != null && !keyword.trim().isEmpty()) {
                List<CourseEntity> allCourses = courseService.getAllCourses();
                courses = allCourses.stream()
                        .filter(course ->
                                course.getCourseName().toLowerCase().contains(keyword.toLowerCase()) ||
                                        (course.getCategory() != null &&
                                                course.getCategory().toLowerCase().contains(keyword.toLowerCase())))
                        .collect(Collectors.toList());
            }
            // 无参数时返回所有课程
            else {
                courses = courseService.getAllCourses();
            }

            log.info("成功搜索到{}个课程", courses.size());
            return ApiResponse.success("课程搜索成功", courses);
        } catch (Exception e) {
            log.error("搜索课程失败: category={}, keyword={}", category, keyword, e);
            return ApiResponse.fail("搜索课程失败: " + e.getMessage());
        }
    }
}
